package com.ydm.fire_fighting_web.modules.management.managementInstitutions.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.ydm.fire_fighting_web.entity.management.MIListRequest;
import com.ydm.fire_fighting_web.entity.management.ManagementInstitutions;
import com.ydm.fire_fighting_web.exception.ExceptionCast;
import com.ydm.fire_fighting_web.exception.response.CommonCode;
import com.ydm.fire_fighting_web.exception.response.QueryResult;
import com.ydm.fire_fighting_web.exception.response.ResponseResult;
import com.ydm.fire_fighting_web.modules.management.managementInstitutions.mapper.ManagementInstitutionsMapper;
import com.ydm.fire_fighting_web.modules.management.managementInstitutions.mapper.ManagementInstitutionsRepository;
import com.ydm.fire_fighting_web.modules.management.managementInstitutions.service.ManagementInstitutionsService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class ManagementInstitutionsServiceImpl  implements ManagementInstitutionsService{
    @Autowired
    private ManagementInstitutionsMapper managementInstitutionsMapper;
    @Autowired
    private ManagementInstitutionsRepository managementInstitutionsRepository;

    @Override
    public QueryResult<ManagementInstitutions> findAll() {
        List<ManagementInstitutions> institutionsList = managementInstitutionsRepository.findAll();
        QueryResult<ManagementInstitutions> MIQueryResult = new QueryResult<ManagementInstitutions>();
        MIQueryResult.setList(institutionsList);
        return MIQueryResult;
    }

    @Override
    public QueryResult<ManagementInstitutions> findListByPage(Integer page, Integer size, MIListRequest miListRequest) {
        if(page<=0){
            page=1;
        }
        if(size<=0){
            size=10;
        }
        if(miListRequest == null){
            miListRequest = new MIListRequest();
        }
        PageHelper.startPage(page, size);
        Page<ManagementInstitutions> byPage = managementInstitutionsMapper.findListByPage(miListRequest);
        List<ManagementInstitutions> list = byPage.getResult();
        long total = byPage.getTotal();
        QueryResult<ManagementInstitutions> MIQueryResult = new QueryResult<ManagementInstitutions>();
        MIQueryResult.setList(list);
        MIQueryResult.setTotal(total);
        return MIQueryResult;
    }

    @Override
    public ResponseResult save(ManagementInstitutions managementInstitutions) {
        ManagementInstitutions byMiName = managementInstitutionsRepository.findByMiName(managementInstitutions.getMiName());
        if(StringUtils.isEmpty(byMiName)){
            return  new ResponseResult(CommonCode.Existing);
        }
        ManagementInstitutions save = managementInstitutionsRepository.save(managementInstitutions);
        return  new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    public ManagementInstitutions findById(String id) {
        Optional<ManagementInstitutions> byId = managementInstitutionsRepository.findById(id);
        if(byId.isPresent()){
            ManagementInstitutions managementInstitutions = byId.get();
            return managementInstitutions;
        }
        ExceptionCast.cast(CommonCode.MI_GET_NOTEXISTS);
        return null;
    }

    @Override
    public ResponseResult update(String id,ManagementInstitutions managementInstitutions) {
        if(StringUtils.isEmpty(id)){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        if(StringUtils.isEmpty(managementInstitutions)){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        ManagementInstitutions one = this.findById(id);
        if(one==null){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        //修改机构信息
        one.setMiName(managementInstitutions.getMiName());
        one.setAddress(managementInstitutions.getAddress());
        one.setPhoneName(managementInstitutions.getPhoneName());
        one.setPhoneTel(managementInstitutions.getPhoneTel());
        ManagementInstitutions save = managementInstitutionsRepository.save(one);
        return new ResponseResult(CommonCode.SUCCESS);
    }
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    @Override
    public ResponseResult batchImport(String fileName, MultipartFile file) {
        boolean notNull = false;
        List<ManagementInstitutions> managementInstitutionsList = new ArrayList<>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            ExceptionCast.cast(CommonCode.UploadFormat);
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = null;
        try {
            is = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Workbook wb = null;
        if (isExcel2003) {
            try {
                wb = new HSSFWorkbook(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                wb = new XSSFWorkbook(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Sheet sheet = wb.getSheetAt(0);
        if(sheet!=null){
            notNull = true;
        }
        ManagementInstitutions managementInstitutions;
        for (int r = 2; r <= sheet.getLastRowNum(); r++) {//r = 2 表示从第三行开始循环 如果你的第三行开始是数据
            Row row = sheet.getRow(r);//通过sheet表单对象得到 行对象
            if (row == null){
                continue;
            }

            //sheet.getLastRowNum() 的值是 10，所以Excel表中的数据至少是10条；不然报错 NullPointerException

            managementInstitutions = new ManagementInstitutions();
            if( row.getCell(0).getCellType() !=1){//循环时，得到每一行的单元格进行判断
                ExceptionCast.cast(CommonCode.Format);
            }
            String miname = row.getCell(1).getStringCellValue();//得到每一行第一个单元格的值
            String address = row.getCell(2).getStringCellValue();//得到每一行第一个单元格的值
            String phone_name = row.getCell(3).getStringCellValue();//得到每一行第一个单元格的值
            String phone_tel = row.getCell(4).getStringCellValue();//得到每一行第一个单元格的值
            //完整的循环一次 就组成了一个对象
            managementInstitutions.setMiName(miname);
            managementInstitutions.setAddress(address);
            managementInstitutions.setPhoneName(phone_name);
            managementInstitutions.setPhoneTel(phone_tel);
            managementInstitutionsList.add(managementInstitutions);
        }
        for (ManagementInstitutions managementInstitutions1 : managementInstitutionsList) {
            String name = managementInstitutions1.getMiName();
            managementInstitutionsRepository.save(managementInstitutions1);
        }
        return new ResponseResult(CommonCode.SUCCESS);
    }
}
